<template>
<div>
  <n-spin :show="loading">
        <n-space>
            <n-card @click="handleAddClick" class="card" hoverable
                content-style="cursor: pointer;color: rgb(186, 186, 186);height: 100%;display: flex;align-items: center;justify-content: center;text-align: center;">
                <n-space vertical>
                    <n-icon size="100">
                        <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 512 512">
                            <path
                                d="M368.5 240H272v-96.5c0-8.8-7.2-16-16-16s-16 7.2-16 16V240h-96.5c-8.8 0-16 7.2-16 16 0 4.4 1.8 8.4 4.7 11.3 2.9 2.9 6.9 4.7 11.3 4.7H240v96.5c0 4.4 1.8 8.4 4.7 11.3 2.9 2.9 6.9 4.7 11.3 4.7 8.8 0 16-7.2 16-16V272h96.5c8.8 0 16-7.2 16-16s-7.2-16-16-16z" />
                        </svg>
                    </n-icon>
                    <span>定时任务添加</span>
                </n-space>
            </n-card>

            <task-card :item="item" v-for="item in list" @execute-now="executeNow" @change-status="changeStatus"
                @delete-task="handleDelJob" @edit-task="handleEditClick" />
        </n-space>
        <template #description>
        加载中，请稍后....
      </template>
    </n-spin>
    <n-space justify="center" v-if="list.length == pageObj.size">
        <n-button strong secondary type="tertiary" @click="loadMore">
            <template #icon>
                <icon-ri:add-circle-fill/>
            </template>
          加载更多
        </n-button>
    </n-space>

    <n-modal v-model:show="showModal" title="编辑" display-directive="if" :bordered="false" preset="card" class="w-500px"
        size="huge" :closable="false">
        <slef-form :formData="formData" @close="handleCloseModal" @list="getList"></slef-form>
    </n-modal>
</div>
</template>

<script  setup lang='ts' >
import { ref, onMounted, reactive } from 'vue';
import { NSpace } from 'naive-ui';
import { useLoading } from '@/hooks';
import { fetchJobPage, fetchJob, fetchDelJob, fetchChangeStatus ,fetchExecuteOnce} from '@/service/api/sys/job'
import TaskCard from "./task-card.vue"
import slefForm from "./form.vue"
import { SysJob } from "./index"
interface DataSource extends SysJob { }
interface SearchForm {
    invokeTarget?: string;
    cronExpression?: string;
    misfirePolicy?: string;
    concurrent?: string;
    status?: string;
}

const searchForm = reactive({ value: initSearchFormData() });
const list = ref<DataSource[]>([]);
const checkRows = ref<DataSource[]>([]);
const { loading, startLoading, endLoading, setEmpty } = useLoading();
const pageObj = reactive<Common.Page<DataSource>>({ total: 0, size: 20, current: 1 })

const showModal = ref(false);
const formData = ref<DataSource>(initFormData())

async function getList() {
    checkRows.value = []
    startLoading()
    const { data } = await fetchJobPage(pageObj, searchForm.value)
    pageObj.total = data?.total ? data.total : 0;
    list.value = data?.records || []
    setEmpty(!list.value.length)
    endLoading()
}
function initSearchFormData(): SearchForm {
    return {}
}
function initFormData(): DataSource {
    return {
        status: "0"
    }
}

async function handleDelJob(row: DataSource): Promise<boolean> {
    if (!row || !row.jobId) {
        window.$message?.error("数据id异常,请刷新后重试")
        return false
    }
    await fetchDelJob([row.jobId])
    getList()
    return true
}

async function handleEditClick(row: DataSource) {
    if (!row || !row.jobId) {
        window.$message?.error("当前行数据异常,请刷新后重试")
        return;
    }
    const { data } = await fetchJob(row.jobId)
    formData.value = data!;
    showModal.value = true;
}

function handleAddClick() {
    formData.value = initFormData();
    showModal.value = true;
}
function handleCloseModal() {
    formData.value = initFormData();
    showModal.value = false;
}

function executeNow(jobId: number) {
    //立即执行
    fetchExecuteOnce(jobId).then(res =>{
        if(!res.error){
            window.$message?.success("执行已完成！")
        }
    })
}

async function changeStatus(jobId: number, status: string) {
    const { data } = await fetchChangeStatus(jobId, status);
    if (data)
        window.$message?.success("操作成功！")
    getList();
}

function loadMore() {
    pageObj.size += 20
    getList()
}

onMounted(() => {
    getList()
})
</script>

<style lang='scss' scoped>
</style>

